#include "aoi.h"

extern UART_HandleTypeDef huart1;

void AOI_powerOn(void)
{
	LL_GPIO_SetOutputPin(LCD3V3_EN_GPIO_Port, LCD3V3_EN_Pin);
	HAL_Delay(100);
}

void AOI_powerOff(void)
{
	//P1 = 0x00;
	LL_GPIO_WriteOutputPort(GPIOA, 0x00);
	//P2 = 0x00;
	LL_GPIO_WriteOutputPort(GPIOB, 0x00);
	//VDD = 1;
	LL_GPIO_ResetOutputPin(LCD3V3_EN_GPIO_Port, LCD3V3_EN_Pin);
	//P4 = 0xff;
	HAL_Delay(1000);
}

void keyWaitRelease(void)
{
	//key = 1;
	while (1) {
		//key = 1;
		HAL_Delay(5);

		if (!LL_GPIO_IsInputPinSet(KEY_GPIO_Port, KEY_Pin)) {
			//key = 1;
			HAL_Delay(25);
			if (!LL_GPIO_IsInputPinSet(KEY_GPIO_Port, KEY_Pin)) {
				while (!LL_GPIO_IsInputPinSet(KEY_GPIO_Port, KEY_Pin)) {
					HAL_Delay(5);
				}
				break;
			}
		}
	}
	/*while(key == 1){
		key = 1;
		HAL_Delay(20);
	}*/
}

void UartSendByte(uint8_t dat)
{
	uint8_t txb[1];
	txb[0] = dat;
	HAL_UART_Transmit(&huart1, txb, 1, HAL_MAX_DELAY);
}

void aoi(void)
{
	//uint8_t txb[64];
	/*
	while(1){
		UartSendByte(0x55);	
		HAL_Delay(100);

		LL_GPIO_SetOutputPin(EXTB_Port, EXTB_Pin);
		HAL_Delay(100);
		AOI_powerOn();
		HAL_Delay(100);

		AOI_test();

		AOI_powerOff();
		HAL_Delay(100);
		UartSendByte(0xaa);
	}
	*/

	uint8_t rxb = 0x00;
	uint8_t flagRunning = 0x01;
	AOI_powerOff();
	HAL_Delay(100);
	AOI_powerOn();
	AOI_reset();
	AOI_init();
	AOI_full();

	UartSendByte(0xAA);
	UartSendByte(0x55);
	HAL_Delay(1000);

	for (;;) {
		rxb = 0x00;
		flagRunning = 0x01;

		HAL_Delay(100);
		AOI_powerOff();
		HAL_Delay(100);

		keyWaitRelease();
		HAL_Delay(100);
		AOI_powerOn();
		AOI_reset();
		AOI_init();
		AOI_full();
		UartSendByte(0x3F);

		while (flagRunning == 0x01) {
			rxb = 0;
			HAL_UART_Receive(&huart1, &rxb, 1, 100);
			if (rxb != 0) {
				switch (rxb) {
				case 0x3E:
					flagRunning = 0;
					UartSendByte(0x3E);
					break;
				case 0x3F:
					AOI_full();
					UartSendByte(0x3F);
					break;
				case 0x30:
					AOI_clear();
					UartSendByte(0x30);
					break;
				case 0x31:
					AOI_img1();
					UartSendByte(0x31);
					break;
				case 0x32:
					AOI_img2();
					UartSendByte(0x32);
					break;
				case 0x33:
					AOI_img3();
					UartSendByte(0x33);
					break;
				case 0x34:
					AOI_img4();
					UartSendByte(0x34);
					break;
				default:
					break;
				}
			}
		}
	}
}